package com.xiaxiang.xiawan.Util;

import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.os.Environment;
import android.util.Log;

import com.xiaxiang.xiawan.XXConfigData;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
 * Created by Administrator on 2017-10-28.
 */

/**
 * Created by Spring on 2015/11/7.
 */
public class FileUtil {
    public static String SDPATH;
    public static String mUnity3dDownloadFolder = "";
    public static final String ASSETS = "assets/";
    public FileUtil() {
        mUnity3dDownloadFolder = SDPATH +"/"+ASSETS;

    }

    public static String getNameByUrl(String url){
        String[] strs = url.split("/");
        return strs[strs.length -1];
    }
    public static String getUnity3dDownloadFolder(){
        return XXConfigData.getCachePath()+ASSETS;
    }
    public String getSDPATH() {
        return SDPATH;
    }

    public FileUtil(String SDPATH) {
        //得到外部存储设备的目录（/SDCARD）
        /*
        SDPATH = Environment.getExternalStorageDirectory() + "/";
        File file = new File(SDPATH);
        if(!file.exists()){
            SDPATH = "/mnt/emmc/";
        }
        Log.e("ret"," SDPATH is "+SDPATH);
        */
    }

    /**
     * 在SD卡上创建文件
     *
     * @param fileName
     * @return
     * @throws java.io.IOException
     */
    public File createSDFile(String fileName) throws IOException {
        File file = new File(fileName);
        file.createNewFile();
        return file;
    }

    /**
     * 在SD卡上创建目录
     *
     * @param dirName 目录名字
     * @return 文件目录
     */
    public File createDir(String dirName) {
        File dir = new File(SDPATH + dirName);
        dir.mkdir();
        return dir;
    }

    /**
     * 判断文件是否存在
     *
     * @param fileName
     * @return
     */
    public boolean isFileExist(String fileName) {
        File file = new File(SDPATH + fileName);
        return file.exists();
    }

    public File write2SDFromInput(String fileName, InputStream input) {
        File file = null;
        OutputStream output = null;
        try {
            Log.e("ret","fileName is "+(getUnity3dDownloadFolder() + fileName));
            file = createSDFile(getUnity3dDownloadFolder() + fileName);
            output = new FileOutputStream(file);
            byte[] buffer = new byte[4 * 1024];
            int ret = 0;
            while ((ret = input.read(buffer)) != -1) {
                output.write(buffer,0,ret);
                output.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }
}
